#define CONV(x) (struct sockaddr *)x
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
class UdpClient
{
public:
    UdpClient() : _sockfd(-1), isconnect(false)
    {
        memset(&_server, 0, sizeof(_server));
    }
    ~UdpClient()
    {
        if (_sockfd >= 0)
        {
            close(_sockfd);
        }
    }
    bool connect(const std::string &serverip, uint16_t serverport)
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            std::cerr << "socket error" << std::endl;
            return false;
        }

        _server.sin_family = AF_INET;
        _server.sin_port = htons(serverport);
        int result = inet_pton(AF_INET, serverip.c_str(), &_server.sin_addr);
        if (result <= 0)
        {
            if (result == 0)
            {
                std::cerr << "Invalid IP address format: " << serverip << std::endl;
            }
            else
            {
                std::cerr << "inet_pton error" << std::endl;
            }
            return false;
        }
        isconnect = true;
        return true;
    }

    bool send(const std::string &message)
    {
        if (!isconnect)
        {
            std::cerr << "not connect" << std::endl;
            return false;
        }
        ssize_t n = sendto(_sockfd, message.c_str(), message.size(), 0, CONV(&_server), sizeof(_server));
        if (n < 0)
        {
            std::cerr << "sendto error" << std::endl;
            return false;
        }
        return true;
    }

    bool recv(std::string &message)
    {
        if (!isconnect)
        {
            std::cerr << "not connect" << std::endl;
            return false;
        }
        char buffer[1024];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&temp), &len);
        if (n < 0)
        {
            std::cerr << "recvfrom error" << std::endl;
            return false;
        }
        buffer[n] = '\0';
        message = buffer;
        return true;
    }

    void disconnect()
    {
        if (_sockfd >= 0)
        {
            close(_sockfd);
            _sockfd = -1;
        }
        isconnect = false;
    }

    bool isConnected() const
    {
        return isconnect;
    }

private:
    int _sockfd;
    struct sockaddr_in _server;
    bool isconnect;
};